package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/websocket"
)

func main() {
	http.HandleFunc("/ws", handleWebSocket)

	log.Fatal(http.ListenAndServe(":9090", nil))
}

func handleWebSocket(writer http.ResponseWriter, request *http.Request) {
	u := &websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := u.Upgrade(writer, request, nil)
	if err != nil {
		fmt.Printf("can not upgrader: %+v", err)
		return
	}

	done := make(chan struct{})
	go func() {
		for {
			m := make(map[string]int)
			err := conn.ReadJSON(&m)
			if err != nil {
				if !websocket.IsCloseError(
					err,
					websocket.CloseGoingAway,
					websocket.CloseNormalClosure,
				) {
					fmt.Printf("unexpected read error: %+v", err)
				}

				done <- struct{}{}
				return
			}
			fmt.Println("message received: ", m)
		}
	}()

	i := 0
	for {
		select {
		case <-time.After(time.Second):
			i++
			err := conn.WriteJSON(map[string]interface{}{
				"hello":  "websocket",
				"msg_id": i,
			})
			if err != nil {
				fmt.Printf("can not write json %+v \n", err)
				return
			}
		case <-done:
			return
		}
	}
}

func handleHttp(writer http.ResponseWriter, request *http.Request) {
	fmt.Fprintf(writer, "hello websocket")
}
